import requests
import toml


class MediaUpload():
    def __init__(self):
        self._cfg = toml.load('settings/config.toml')
        self._get_token_url = self._cfg['DINGROBOT']['get_token_url']
        self._upload_media_url = self._cfg['DINGROBOT']['upload_media_url']
        self._appkey = self._cfg['DINGROBOT']['appkey']
        self._appsecret = self._cfg['DINGROBOT']['appsecret']
        # self._access_token = self._cfg['DINGROBOT']['access_token']

    def get_access_token(self):
        get_token = requests.get(f"{self._get_token_url}?appkey={self._appkey}&appsecret={self._appsecret}")
        access_token = get_token.json()['access_token']
        # print(access_token)
        self._cfg['DINGROBOT']['access_token'] = access_token

        with open('settings/config.toml', 'w') as f:
            toml.dump(self._cfg, f)
        return access_token
    def upload_media_to_dingtalk(self,image_path):
        access_token = self.get_access_token()
        with open(image_path,'rb') as file:
            files = {'media':file}
            response = requests.post(f"{self._upload_media_url}?access_token={access_token}&type=image",files = files)
            # print(response.json())
            media_id = response.json()['media_id']
            # print(media_id)
            return media_id
